package com.lagou.rpc.provider.zk;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Component;

/**
 * @author lihongfeng
 */
@Component
public class ZkUtil {

    private final String parentPath = "/rpc-server";
    ZkClient zkClient;

    public ZkUtil() {
        zkClient = new ZkClient("127.0.0.1:2181");
    }

    /**
     * 把服务器地址注册到zk中
     *
     * @param ip   -
     * @param port -
     */
    public void addNode(String ip, Integer port) {
        System.out.println("服务端ZK会话被创建了..");
        if (!zkClient.exists(parentPath)) {
            zkClient.createPersistent(parentPath);
        }
        //监听
        //创建临时节点
        zkClient.createEphemeral(parentPath + "/" + ip + "-" + port);
    }

    public void subscribeChildChanges() {
        //这块建立监听
        zkClient.subscribeChildChanges(parentPath, (s, list) -> System.out.println(parentPath + "的子节点列表发生了变化,变化后的子节点列表为" + list));
    }
}
